<template>
    <div>
        <div>
            <el-row>
                <el-tabs
                    ref="filterTabs"
                    v-model="listTabActive"
                    @tab-click="listTabChange"
                    type="card"
                >
                    <el-tab-pane name="myIssues">
                        <span slot="label">
                            <i class="el-icon-date"></i> 我的任务
                            <el-badge
                                v-if="myIssuesCount > 0"
                                :value="myIssuesCount"
                                class="tab-content-badge"
                            ></el-badge>
                        </span>
                    </el-tab-pane>
                    <el-tab-pane name="myAssigned">
                        <span slot="label">
                            <i class="el-icon-date"></i> 我已承接
                            <el-badge
                                v-if="myAssignedCount > 0"
                                :value="myAssignedCount"
                                class="tab-content-badge"
                            ></el-badge>
                        </span>
                    </el-tab-pane>
                </el-tabs>
            </el-row>
            <div>
                <!--筛选条件-->
                <el-form
                    :model="filterForm"
                    label-width="70px"
                >
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="病理编号">
                                <el-input
                                    v-model="filterForm.pathologyId"
                                    placeholder="请输入病理编号"
                                    class="input-form"
                                    size="mini"
                                >
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="申请时间">
                                <el-date-picker
                                    v-model="createdRange"
                                    class="time-picker-form"
                                    size="mini"
                                    type="daterange"
                                    align="right"
                                    unlink-panels
                                    range-separator="-"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col
                            :span="6"
                            :offset="6"
                        >
                            <div
                                class="expansion"
                                @click="showExpansion = !showExpansion"
                            >
                                <font-awesome-icon
                                    v-if="!showExpansion"
                                    :icon="['fas', 'angle-down']"
                                >
                                </font-awesome-icon>
                                <font-awesome-icon
                                    v-else
                                    :icon="['fas', 'angle-up']"
                                >
                                </font-awesome-icon>
                            </div>
                            <el-button
                                @click="search"
                                size="mini"
                                style="margin-left: 15px"
                            >
                                <font-awesome-icon :icon="['fas', 'search']">
                                </font-awesome-icon>
                            </el-button>
                        </el-col>
                    </el-row>

                    <!--dispatcher扩展筛选-->
                    <div v-if="showExpansion">
                        <el-row>
                            <el-col :span="6">
                                <el-form-item label="患者姓名">
                                    <el-input
                                        v-model="filterForm.name"
                                        placeholder="请输入患者姓名"
                                        class="input-form"
                                        size="mini"
                                    >
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="患者性别">
                                    <el-radio-group
                                        v-model="filterForm.sex"
                                        class="radio-group"
                                        size="mini"
                                    >
                                        <el-radio
                                            v-for="sex in sexKindList"
                                            :key="sex.id"
                                            :label="sex.id"
                                            :value="sex.id"
                                        >
                                            {{ sex.name }}
                                        </el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="6">
                                <el-form-item label="检查类型">
                                    <el-select
                                        v-model="filterForm.checkCategory"
                                        placeholder="请选择检查类型"
                                        clearable
                                        class="picker-form"
                                        size="mini"
                                    >
                                        <el-option
                                            v-for="item in checkCategoryList"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="患者年龄">
                                    <el-row>
                                        <el-col :span="10">
                                            <el-input
                                                v-model="filterForm.startAge"
                                                placeholder="起始年龄"
                                                class="input-form"
                                                size="mini"
                                            ></el-input>
                                        </el-col>
                                        <el-col
                                            :span="2"
                                            class="link-line"
                                        >-</el-col>
                                        <el-col :span="10">
                                            <el-input
                                                v-model="filterForm.endAge"
                                                placeholder="结束年龄"
                                                class="input-form"
                                                size="mini"
                                            ></el-input>
                                        </el-col>
                                    </el-row>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="身份证号">
                                    <el-input
                                        v-model="filterForm.cardId"
                                        placeholder="请输入身份证号"
                                        class="input-form"
                                        size="mini"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="6">
                                <el-form-item label="送检医生">
                                    <el-input
                                        v-model="filterForm.sendDoctor"
                                        placeholder="请输入送检医生"
                                        class="input-form"
                                        size="mini"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="联系电话">
                                    <el-input
                                        v-model="filterForm.sendDoctorTel"
                                        placeholder="请输入联系电话"
                                        class="input-form"
                                        size="mini"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="病区号">
                                    <el-input
                                        v-model="filterForm.wardId"
                                        placeholder="请输入病区号"
                                        class="input-form"
                                        size="mini"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="6">
                                <el-form-item label="取材部位">
                                    <el-input
                                        v-model="filterForm.sampleBody"
                                        placeholder="请输入取材部位"
                                        class="input-form"
                                        size="mini"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="取材脏器">
                                    <el-select
                                        v-model="filterForm.sampleOrganId"
                                        placeholder="请选择取材脏器"
                                        clearable
                                        size="mini"
                                        class="picker-form"
                                    >
                                        <el-option
                                            v-for="(organ, index) in sampleOrganList"
                                            :key="index"
                                            :label="organ.name"
                                            :value="organ.id"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="床位号">
                                    <el-input
                                        v-model="filterForm.bedId"
                                        placeholder="请输入患者年龄"
                                        class="input-form"
                                        size="mini"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="6">
                                <el-form-item label="标本名称">
                                    <el-input
                                        v-model="filterForm.specimenName"
                                        placeholder="请输入患者年龄"
                                        class="input-form"
                                        size="mini"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="标本类别">
                                    <el-select
                                        v-model="filterForm.specimenType"
                                        placeholder="请选择标本类别"
                                        clearable
                                        class="picker-form"
                                        size="mini"
                                    >
                                        <el-option
                                            v-for="item in specimenCategoryList"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </el-form>
            </div>
            <el-row>
                <base-table
                    ref="diagnosisTable"
                    v-loading="!diagnosisTable.isReady"
                    :data="diagnosisTable.data"
                    :header="diagnosisTable.header"
                    :operation="diagnosisTable.operation"
                    :pageInfo="diagnosisTable.pageInfo"
                    :cellStyleFunc="diagnosisTableCellStyleFunc"
                    :buttonVisibleFunc="diagnosisTableButtonVisibleFunc"
                    :pageSizes="[5, 10, 15]"
                    @handleClick="diagnosisTableButtonClick"
                    @pageJumpTo="diagnosisTablePageJumpTo"
                    @sizeChange="diagnosisTableSizeChange"
                >
                </base-table>
            </el-row>
        </div>
    </div>
</template>

<script>
import BaseTable from '@templates/components/BaseTable';
import moment from 'moment/moment';
import { DateUtil } from '@/client/libs/date';
export default {
    name: 'ViewDiagnosisList',
    components: {
        BaseTable,
    },
    data() {
        return {
            listTabActive: 'myIssues',

            tabCountRequestList: [
                {
                    url: '/diagnosis/tasks',
                    countKey: 'myIssuesCount',
                },
                {
                    url: '/diagnosis/finished',
                    countKey: 'myAssignedCount',
                },
            ],

            waitingAssignCount: 0,
            myIssuesCount: 0,
            myAssignedCount: 0,
            filterForm: {
                pathologyId: '',
                name: '',
                sampleOrganId: '', // 取材脏器
                sendDoctor: '', // 送检医生
                checkCategory: '', // 检查类型
                startAge: '',
                endAge: '',
                cardId: '',
                sex: '',
                wardId: '',
                bedId: '',
                sampleBody: '', // 取材部位
                sendDoctorTel: '', // 联系电话
                specimenName: '', // 标本名称
                specimenType: '', // 标本类别
                scanDateEnd: '', // 最小创建时间
                scanDateStart: '', // 最大创建时间
            },
            createdRange: [],
            showExpansion: false,
            checkCategoryList: [],
            sexKindList: [],
            specimenCategoryList: [],
            freezeAndCommonTimeList: [], // 保存冰冻常规对应的超时时间
            specimenCategoryTimeList: [], // 保存标本类别对应的超时时间
            // 取材脏器列表
            sampleOrganList: [],
            // 所需字典对应表
            dictRequestMap: [
                {
                    code: 'checkCategory',
                    arrayKey: 'checkCategoryList',
                },
                {
                    code: 'SexKind',
                    arrayKey: 'sexKindList',
                },
                {
                    code: 'specimenCategory',
                    arrayKey: 'specimenCategoryList',
                },
                {
                    code: 'freezeType',
                    arrayKey: 'freezeAndCommonTimeList',
                },
                {
                    code: 'specimenCategory',
                    arrayKey: 'specimenCategoryTimeList',
                },
            ],
            filterTemp: {},
            diagnosisTable: {
                isReady: false,
                data: [{ id: 276, pathologyId: '1234' }],
                header: [
                    {
                        label: '倒计时',
                        prop: 'createTime',
                        width: '120',
                        isRender: true,
                        render: (h, params) => {
                            let _vm = this;
                            let _c = _vm._self._c || _h;

                            let currentTime = _vm.freezeAndCommonTimeList.find(
                                (item) => {
                                    return (
                                        item.name === params.row.freezeTypeName
                                    );
                                }
                            );
                            if (!currentTime || currentTime.name === '常规') {
                                currentTime = _vm.specimenCategoryTimeList.find(
                                    (item) => {
                                        return (
                                            item.name ===
                                            params.row.specimenTypeName
                                        );
                                    }
                                );
                            }
                            const hour = currentTime
                                ? parseFloat(currentTime.firstCode)
                                : undefined;
                            let dateContent = null;
                            let offsetTime = null;
                            if (hour) {
                                offsetTime = DateUtil.offset({
                                    dateTime: DateUtil.parseDate(
                                        params.row.createTime
                                    ),
                                    hours: hour,
                                });
                                const day = new Date(offsetTime).getDay();
                                if (day === 6 || day === 0) {
                                    offsetTime = DateUtil.offset({
                                        dateTime: DateUtil.parseDate(
                                            params.row.createTime
                                        ),
                                        hours: hour + 48,
                                    });
                                }
                                dateContent = DateUtil.friendlyDate(
                                    offsetTime,
                                    '已超时'
                                );
                            }
                            return h('span', [
                                h(
                                    'el-tooltip',
                                    {
                                        attrs: {
                                            effect: 'dark',
                                            placement: 'top',
                                        },
                                    },
                                    [
                                        h('div', {
                                            attrs: { slot: 'content' },
                                            domProps: {
                                                innerHTML: dateContent
                                                    ? '送检时间 : ' +
                                                      params.row.createTime +
                                                      '</br>' +
                                                      '要求出报告时间 : ' +
                                                      offsetTime +
                                                      '</br>' +
                                                      '剩余时间 : ' +
                                                      dateContent.content +
                                                      '</br>'
                                                    : '',
                                            },
                                            slot: 'content',
                                        }),
                                        h(
                                            'span',
                                            {
                                                style: {
                                                    color:
                                                        !!dateContent &&
                                                        dateContent.isfuture
                                                            ? '#67C23A'
                                                            : '#F56C6C',
                                                },
                                            },
                                            !!dateContent
                                                ? dateContent.content
                                                : ''
                                        ),
                                    ]
                                ),
                            ]);
                        },
                    },
                    {
                        label: '病理编号',
                        prop: 'pathologyId',
                    },
                    {
                        label: '切片数',
                        prop: 'biopsyCount',
                    },
                    {
                        label: '患者姓名',
                        prop: 'name',
                    },
                    {
                        label: '送检医生',
                        prop: 'sendDoctor',
                    },
                    {
                        label: '患者年龄',
                        prop: 'age',
                    },
                    {
                        label: '性别',
                        prop: 'sex',
                    },
                    {
                        label: '送检科室',
                        prop: 'sendDepartment',
                    },
                    {
                        label: '取材部位',
                        prop: 'sampleBody',
                    },
                    {
                        label: '取材脏器',
                        prop: 'sampleOrganName',
                    },
                ],
                operation: [
                    {
                        label: '查看',
                        functionKey: 'diagnosisTableDetail',
                    },
                ],
                pageInfo: {
                    page: 1,
                    size: 15,
                    total: 0,
                },
            },
        };
    },
    async mounted() {
        this.diagnosisTableRequest();
        this.dictionariesRequest();
        // 获取脏器数据
        this.sampleOrganRequest();
    },
    computed: {
        canAssignBySelf() {
            return true;
        },
        requestUrl() {
            if (this.listTabActive === 'waitingAssign') {
                return '/diagnosis/wait-dispatch';
            }
            if (this.listTabActive === 'myIssues') {
                return '/diagnosis/tasks';
            }
            if (this.listTabActive === 'myAssigned') {
                return '/diagnosis/finished';
            }
            return '';
        },
    },
    methods: {
        // 请求字典信息
        dictionariesRequest() {
            this.dictRequestMap.forEach((map) => {
                this.$axios({
                    method: 'GET',
                    url: '/PROXY-Remote/dicts/list',
                    params: {
                        code: map.code,
                        page: 0,
                        size: 99,
                    },
                }).then((res) => {
                    if (res && res.data.code === 200) {
                        this[map.arrayKey] = _.clone(res.data.data);

                        if (map.code === 'SexKind') {
                            this[map.arrayKey].push({
                                id: '',
                                name: '全部',
                            });
                        }
                    }
                });
            });
        },
        // 请求脏器信息
        sampleOrganRequest() {
            this.$axios({
                // 详见 axios 请求配置项
                method: 'GET',
                url: '/PROXY-Remote/organs',
                params: {
                    size: 10000,
                },
            }).then((res) => {
                if (res && res.data.code === 200) {
                    res.data.data.forEach((t) => {
                        this.sampleOrganList.push({
                            id: t.id,
                            name: t.name,
                        });
                    });
                }
            });
        },
        // 对年龄进行判断
        ageValidate() {
            // 判断年龄格式
            if (this.filterForm.startAge) {
                const age = _.toNumber(this.filterForm.startAge);
                if (typeof age !== 'number' || Number.isNaN(age)) {
                    this.$message.warning('年龄必须为数字！');
                    return false;
                }
            }
            if (this.filterForm.endAge) {
                const age = _.toNumber(this.filterForm.endAge);
                if (typeof age !== 'number' || Number.isNaN(age)) {
                    this.$message.warning('年龄必须为数字！');
                    return false;
                }
            }
            // 判断年龄范围
            if (this.filterForm.startAge && this.filterForm.endAge) {
                if (this.filterForm.startAge >= this.filterForm.endAge) {
                    this.$message.warning('起始年龄应该小于结束年龄!');
                    return false;
                }
            }
            return true;
        },
        search() {
            if (!this.ageValidate()) {
                return false;
            }
            // 确定时间范围
            if (this.createdRange && this.createdRange.length > 0) {
                let createTimeStart = '';
                let createTimeEnd = '';
                [createTimeStart, createTimeEnd] = this.createdRange;
                this.filterForm.scanDateEnd = moment(createTimeEnd)
                    .format('YYYY-MM-DD hh:mm:ss')
                    .replace(' ', ' ');
                this.filterForm.scanDateStart = moment(createTimeStart)
                    .format('YYYY-MM-DD hh:mm:ss')
                    .replace(' ', ' ');
            }
            // 保存过滤条件到 Temp
            this.filterTemp = {};
            Object.keys(this.filterForm).forEach((key) => {
                if (this.filterForm[key]) {
                    this.filterTemp[key] = this.filterForm[key];
                }
            });
            // 重置页码
            this.diagnosisTable.pageInfo.page = 1;
            this.diagnosisTableRequest();
            return true;
        },
        listTabChange() {
            this.diagnosisTable.pageInfo.page = 1;
            this.diagnosisTableRequest();
        },
        diagnosisTableButtonClick(functionKey, row) {
            this[functionKey](row);
        },
        diagnosisTableDetail(row) {
            let commitValue = {
                id: row.id,
                pathologyId: row.pathologyId,
                pDiagnosisType: '',
            };
            if (this.listTabActive === 'myIssues') {
                commitValue.pDiagnosisType = 1; //我的任务传0，给/diagnosis/single这个接口的参数 区分是从我的任务点进去的详情，得到上一个下一个病理号，切片浏览器上z,x快捷键才能用
                sessionStorage.setItem('pDiagnosisType', '1');
            } else if (this.listTabActive === 'myAssigned') {
                commitValue.pDiagnosisType = 2; //我已承接传1，给/diagnosis/single这个接口的参数 区分是从我的任务点进去的详情，得到上一个下一个病理号，切片浏览器上z,x快捷键才能用
                sessionStorage.setItem('pDiagnosisType', '2');
            } else {
                commitValue.pDiagnosisType = '';
                sessionStorage.setItem('pDiagnosisType', '');
            }
            this.$store.commit('setPropertyGeneral', {
                key: 'diagnosis',
                value: commitValue,
            });
            sessionStorage.setItem('pathologyId', row.pathologyId);
            if (row.biopsyCount > 0) {
                const { href } = this.$router.resolve({
                    name: 'Viewer',
                    path: '/Viewer',
                    query: {
                        fileName: row.biopsyList.newFilename,
                        originFilename: row.biopsyList.originFilename,
                        pathologyId: row.pathologyId,
                        biopsyId: row.id,
                        userId: this.$route.query.userId,
                        authorization: this.$store.state.authorization,
                    },
                });
                const width = window.screen.availWidth + 10;
                const height = window.screen.availHeight + 10;
                window.open(
                    href,
                    '_self',
                    `location=no,width=${width},height=${height}`
                );
            } else {
                this.$message.info('该诊断不存在切片');
            }
        },
        // TODO 退回
        diagnosisTableDrawBack() {},
        diagnosisTablePageJumpTo(val) {
            this.diagnosisTable.pageInfo.page = val;
            // 为 diagnosisTable.data 赋值相应页上新数据
            this.diagnosisTableRequest();
        },
        diagnosisTableSizeChange(val) {
            this.diagnosisTable.pageInfo.size = val;
            // 为 diagnosisTable.data 赋值相应数据量新数据
            this.diagnosisTableRequest();
        },
        diagnosisTableButtonVisibleFunc(functionKey) {
            switch (functionKey) {
                case 'diagnosisTableAssign':
                    return this.listTabActive === 'waitingAssign';
                case 'diagnosisTableDrawBack':
                    return this.listTabActive === 'myIssues';
                default:
                    return true;
            }
        },
        diagnosisTableCellStyleFunc({ row, column }) {
            const baseStyle = {
                padding: '3px 0',
                'border-right': '1px solid #ffffff',
                'font-size': '14px',
            };
            switch (column.label) {
                case '性别':
                    if (row.sex === '女性') {
                        baseStyle.color = 'red';
                    }
                    if (row.sex === '男性') {
                        baseStyle.color = 'blue';
                    }
                    break;
                case '报告剩余时间':
                    if (row.deadlineTime < 48 * 3600 * 1000) {
                        baseStyle.color = 'red';
                    } else {
                        baseStyle.color = 'green';
                    }
                    break;
                default:
                    break;
            }
            return baseStyle;
        },
        async diagnosisTableRequest() {
            this.diagnosisTable.isReady = false;
            this.diagnosisCountRequest();
            this.filterTemp.size = this.diagnosisTable.pageInfo.size;
            this.filterTemp.page = this.diagnosisTable.pageInfo.page - 1;
            const res = await this.$axios({
                url: `/PROXY-Remote${this.requestUrl}`,
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    authorization: this.$store.state.authorization,
                },
                params: {
                    isShowDispatcher: 0,
                },
                data: this.filterTemp,
            });
            if (res && res.data.code !== 200) {
                this.diagnosisTable.isReady = true;
                throw new Error(res.data);
            }

            // 请求成功
            const result = res.data;
            console.log('result', result);
            // 分页信息
            this.diagnosisTable.pageInfo = {
                total: result.pageInfo.total,
                page: result.pageInfo.page + 1,
                size: result.pageInfo.size,
            };
            // 查询结果数据
            this.diagnosisTable.data = [];
            if (result.data) {
                result.data.forEach((t) => {
                    this.diagnosisTable.data.push({
                        index: this.diagnosisTable.data.length,
                        id: t.id,
                        createTime: t.createTime,
                        pathologyId: t.pathologyId,
                        biopsyCount: t.biopsyList.length,
                        name: t.name,
                        sendDoctor: t.sendDoctor,
                        age: `${t.age ? t.age : ''}${
                            t.ageUnitName ? t.ageUnitName : ''
                        }`,
                        sex: t.sexName,
                        sendDepartment: t.sendDepartment,
                        sampleBody: t.sampleBody,
                        sampleOrganName: t.sampleOrganName,
                        biopsyList: t.biopsyList[0],
                        freezeTypeName: t.freezeTypeName,
                        specimenTypeName: t.specimenTypeName,
                    });
                });
            }

            this.diagnosisTable.isReady = true;
        },
        diagnosisCountRequest() {
            this.tabCountRequestList.forEach(async (t) => {
                await this.$axios({
                    url: `/PROXY-Remote${t.url}`,
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    params: {
                        isShowDispatcher: 0,
                    },
                    data: { size: 10, page: 0 },
                }).then((res) => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }
                    const result = res.data;
                    // 请求成功
                    this[t.countKey] = result.pageInfo.total;
                });
            });
        },
    },
};
</script>

<style scoped>
.expansion {
    width: 30px;
    height: 30px;
    display: inline;
    font-size: 28px;
    line-height: 30px;
    margin-top: 25px;
    vertical-align: middle;
    color: #10a1df;
    cursor: pointer;
}
</style>
